package com.application.common.utils;

import com.jfinal.kit.PathKit;
import net.coobird.thumbnailator.Thumbnails;
import org.apache.commons.io.FileUtils;
import sun.misc.BASE64Decoder;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URL;

public class ImageUtils {

    private static final int IMAGE_W = 400;
    private static final int IMAGE_H = 400;

    public static String zoom(File srcFile, File dstFile) {
        return zoom(srcFile, dstFile, IMAGE_W, IMAGE_H);
    }

    /**
     * 返回压缩完后的文件名
     * png为无损压缩，而jpg
     *
     * @param srcFile
     * @param dstFile
     * @param w
     * @param h
     * @return
     */
    public static String zoom(File srcFile, File dstFile, int w, int h) {
        FileInputStream inputStream = null;
        String dstName = null;
        try {
            if (!dstFile.getParentFile().exists()) {
                dstFile.getParentFile().mkdirs();
            }
//            Thumbnails.of(srcFile)
//                    .outputFormat("jpg")
//                    .size(w, h).toFile(dstFile);

            inputStream = new FileInputStream(srcFile);
            BufferedImage image = ImageIO.read(inputStream);

            //超过最大高度进行等比例压缩,压缩标准最大高度为H
            if (image.getHeight() > h || image.getWidth() > w) {
//                w = (int) (((float) image.getHeight() / image.getWidth()) * h);
                Thumbnails.of(srcFile).size(w, h).outputFormat("jpg").toFile(dstFile);

                dstName = dstFile.getName() + ".jpg";
            } else {

                if (dstFile.exists()) {
                    dstFile.delete();
                }
                dstName = srcFile.getName();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return dstName;
    }


    public static String downloadFile(String url, String storePath) throws IOException {
//        String path = (PathKit.getWebRootPath()+"/exclemodel/").replace("\\", "/");
        URL httpurl = new URL(url);
        File f = new File(PathKit.getWebRootPath() + storePath);
        if(f.getParent() == null){
            f.mkdirs();
        }
        FileUtils.copyURLToFile(httpurl, f);
        if(f.isFile()){
            return storePath;
        }
        return null;
    }


    /**
     * 将Base64图片转换为文件形式
     * @param base64
     * @return
     */
    public static String convertBase64ToImage(String base64, String pathname) {

        String[] parts = base64.split(",");
        String imageString = parts[1];

        // create a buffered image
        BufferedImage image;
        byte[] imageByte;

        BASE64Decoder decoder = new BASE64Decoder();
        try {
            imageByte = decoder.decodeBuffer(imageString);
        } catch (IOException e) {
            return null;
        }

        try (ByteArrayInputStream bis = new ByteArrayInputStream(imageByte)) {
            image = ImageIO.read(bis);
        } catch (IOException e) {
            return null;
        }

        File outputFile = new File(pathname);
        try {
            if(!outputFile.getParentFile().exists()) {
                outputFile.getParentFile().mkdirs();
            }
            outputFile.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
        try {
            final boolean write = ImageIO.write(image, parts[0].split("/")[1].split(";")[0], outputFile);
            System.out.println(write);
        } catch (IOException e) {
            return null;
        }
        return pathname;
    }

    public static void main(String[] args) {
        StringBuffer sb = new StringBuffer(20000);
        convertBase64ToImage(sb.toString(), "d:\\test.jpg");
    }
}
